package mysql

import (
	"fmt"
	"gitee.com/DonHz/qimi/bluebell/config"
	"gitee.com/DonHz/qimi/bluebell/models"
	"go.uber.org/zap"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)
var db *gorm.DB

func Init(cfg *config.MysqlConfig)  {
	dsn:=fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True",
		cfg.User, cfg.Password, cfg.Host, cfg.Port, cfg.DBName,
		)
	var err error
	db, err = gorm.Open(mysql.Open(dsn), &gorm.Config{
		PrepareStmt: true, // SQL预编译，提高查询效率
	})
	if err!= nil{
		zap.L().Error("connect to mysql failed: ", zap.Error(err))
		panic(err)
	}
	err = models.InitTables(db)
	if err!=nil{
		panic(err)
	}
	sqldb, err:=db.DB()
	if err!=nil{
		panic(err)
	}
	sqldb.SetMaxOpenConns(cfg.MaxOpenConns)
	sqldb.SetMaxIdleConns(cfg.MaxIdleConns)
	return
}
